<template>
  <a-card
    okText="提交" 
    cancelText="关闭"
    :title="title"
    :confirmLoading="confirmLoading"
    class="supplier-info"
    @cancel="closeModal()" 
    @ok="handleSubmit">
    <a-form autocomplete="off" :form="form"  :label-col="{ span: 5 }" :wrapper-col="{ span:18 }">
      <h3 class="title">基本信息</h3>
      <a-form-item label="公司名称">
        <a-input
          style="width: 250px"
          :maxLength="60"
          v-decorator="['supplierName',{rules: [{required: true, message: '请输入公司名称'} ]}]"
          placeholder="请输入公司名称"
        />
        <p style="margin-left: 20px" class="form-tips red inline">国际银行开户使用</p>
      </a-form-item>
      <a-form-item label="分销商编码">
        <a-input
          style="width: 250px"
          :maxLength="60"
          :disabled="!!record.id"
          v-decorator="['supplierCode']"
          placeholder="请输入分销商编码"
        />
      </a-form-item>
      <!-- <a-form-item label="组织机构代码">
        <a-input
          style="width: 250px"
          :maxLength="60"
          v-decorator="['orgCode']"
          placeholder="请输入组织机构代码"
        />
      </a-form-item> -->
      <a-form-item label="企业证件类型">
        <a-select
          style="width: 250px"
          v-decorator="['enterpriseIdentificationType']" 
          placeholder="请选择企业证件类型" 
          :options="enterpriseIdentificationTypeOptions"
          allowClear>
        </a-select>
        <p style="margin-left: 20px" class="form-tips red inline">国际银行开户使用</p>
      </a-form-item>
      <a-form-item label="企业证件号码">
        <a-input
          style="width: 250px"
          :maxLength="32"
          v-decorator="['enterpriseIdentificationNumber']"
          placeholder="请输入企业证件号码"
        />
        <p style="margin-left: 20px" class="form-tips red inline">国际银行开户使用</p>
      </a-form-item>
      <a-form-item label="分销商分类">
        <a-select
          style="width: 250px"
          allowClear
          showSearch 
          optionFilterProp="children"
          placeholder="请选择"
          :options="supplierType"
          v-decorator="['supplierTypeId']"
        >
        </a-select>
        <a-button type="link" @click="addType()">新增分销商分类</a-button>
        <a-divider type="vertical" />
        <a-button type="link" @click="getType()" :loading="supplierTypeLoading">刷新</a-button>
      </a-form-item>
      <a-form-item label="物流模式">
        <a-select
          style="width: 250px"
          v-decorator="['logisticsMode']" 
          placeholder="请选择" 
          :options="logisticsModeOptions"
          allowClear>
        </a-select>
      </a-form-item>
      <a-form-item label="分销商地址">
        <a-cascader
          style="width: 250px"
          autocomplete="off"
          :field-names="{ label: 'areaName', value: 'id', children: 'children' }"
          :options="areaTree"
          :show-search="true"
          placeholder="请选择省/市/区"
          v-decorator="[
            'areaIdList',
          ]" />
      </a-form-item>
      <a-form-item label="详细地址">
        <a-textarea
          style="width: 250px"
          :maxLength="100"
          v-decorator="['detailAddress']"
          placeholder="请填写详细地址"
        />
      </a-form-item>


      <h3 class="title">结算信息</h3>
      <a-form-item label="结算方式">
        <a-select
          style="width: 250px"
          v-decorator="['settlementMethod']"
          placeholder="请选择"
          :options="settlementMethodOptions"
          allowClear>
        </a-select>
      </a-form-item>
      <a-form-item label="账期">
        <a-input-number
          :min="0"
          :precision="0"
          v-decorator="['cycleDay']"
          style="width: 250px"
        />&nbsp;天
      </a-form-item>



      <h3 class="title">银行账户信息</h3>
      
      <a-form-item label="付款方式">
        <a-select style="width: 250px" v-decorator="['paymentMethod']" placeholder="请选择" allowClear :options="paymentMethodOptions">
        </a-select>
      </a-form-item>
      <a-form-item label="账户名称">
        <a-input
          style="width: 250px"
          v-decorator="['bankCardName']" placeholder="请输入账户名称"
        />
      </a-form-item>
      <a-form-item label="企业对公账号">
        <a-input
          style="width: 250px"
          :maxLength="32"
          v-decorator="['bankCardNum']"
          placeholder="请输入企业对公账号"
        />
        <p style="margin-left: 20px" class="form-tips red inline">国际银行开户使用</p>
      </a-form-item>
      <a-form-item label="开户银行">
        <a-select
          style="width: 250px"
          show-search
          v-decorator="['bankOpenId']"
          placeholder="请选择或输入开户银行"
          option-filter-prop="children"
          :filter-option="filterOption"
          @change="changeBankOpenName">
          <a-select-option v-for="item in bankOpenNameList" :key="item.value" :value="item.value">{{ item.label }}</a-select-option>
        </a-select>
        <!-- <a-input
          style="width: 250px"
          v-decorator="['bankOpenName']" placeholder="请输入开户银行"
        /> -->
        <p style="margin-left: 20px" class="form-tips red inline">国际银行开户使用</p>
      </a-form-item>
      <a-form-item label="企业预留经办人手机号">
        <a-input
          style="width: 250px"
          v-decorator="['enterpriseOperatorPhone', { rules: phoneRules }]" placeholder="请输入企业预留经办人手机号"
        />
        <p style="margin-left: 20px" class="form-tips red inline">国际银行开户使用</p>
      </a-form-item>
      <a-form-item label="开户地区">
        <a-input
          style="width: 250px"
          v-decorator="['bankOpenArea']" placeholder="请输入开户地区"
        />
      </a-form-item>
      <a-form-item label="支行名称">
        <a-input
          style="width: 250px"
          v-decorator="['bankBranchName']" placeholder="请输入支行名称"
        />
      </a-form-item>
      <a-form-item label="企业名称">
        <a-input
          style="width: 250px"
          v-decorator="['enterpriseName']" placeholder="请输入企业名称"
        />
      </a-form-item>
      <a-form-item label="公司税号">
        <a-input
          style="width: 250px"
          v-decorator="['taxNum']" placeholder="请输入公司税号"
        />
      </a-form-item>

      <!-- <template v-if="!!record.id">
        <h3 class="title">联系人信息</h3>
        <a-form-item  :label-col="{ span: 0 }" :wrapper-col="{ span:24 }">
          <contacts-table :record="record" />
        </a-form-item>
      </template> -->


      <h3 class="title">附件信息</h3>
      <a-form-item label="资质图片文件">
        <upload-image 
          :limit="10"
          v-decorator="['qualificationImages']"
        />
        <p>请上传营业执照等资质文件，支持 png、jpg、jpeg 文件，单个文件不可大于10M </p>
      </a-form-item>
      <a-form-item label="资质文档文件">
        <upload-file 
          :limit="10"
          accept=".pdf"
          v-decorator="['qualificationDocuments']"
        />
        <p>目前仅支持 pdf 格式文件</p>
      </a-form-item>



      <h3 class="title">备注信息</h3>
      <a-form-item label="备注信息">
        <a-textarea
          style="width: 250px"
          v-decorator="['remark']"
          placeholder="请填写备注信息"
        />
      </a-form-item>
    </a-form>
    <type-info :record="typeRecord" @cancel="closeTypeModal" :visible="typeVisible" />
  </a-card>
</template>
<script>
import regex from '@/utils/regex'
import TypeInfo from './components/TypeInfo'
import {getAreaTree} from '@/utils/asyncUtils'
import {treeFindPath} from '@/utils'
import ContactsTable from './components/ContactsTable'
import zip from 'lodash/zip'
export default {
  name: 'supplier-info',
  components: {
    TypeInfo,
    ContactsTable
  },
  props: {
    record: {
      type: Object,
      default() {
        return {}
      }
    },
  },
  computed: {
    title () {
      return this.record.id ? '修改分销商' : '新增分销商'
    },
    
  },
  data () {
    return {
      form: this.$form.createForm(this, { name: 'co1ordinated' }),
      confirmLoading: false,
      supplierTypeLoading: false,
      typeVisible: false,
      typeRecord: {},
      supplierType:[],
      bankOpenName: '',
      bankOpenNameList: [],
      areaTree: [],
      suppStatus:null,
      enterpriseIdentificationTypeOptions: [
        { label:'营业执照', value:1 },
        { label:'其他主体资格证明文件', value:2 }
      ],
      logisticsModeOptions:[{
        label:'统一配送',
        value:1
      }],
      settlementMethodOptions:[{
        label:'先货后款',
        value:1
      }],
      paymentMethodOptions:[{
        label:'银行转账',
        value:1
      }],
      phoneRules: [
        {pattern: regex.phone, message: '请输入正确的手机号'},
      ],
    }
  },
  watch: {},
  created() {
    if (!(this.areaTree && this.areaTree.length)) {
      getAreaTree().then(res => {
        this.areaTree = res
      })
    }
    if(this.record.id){
      this.getInfo()
    }
    this.getType()
    this.getBankOpenNameList()
  },
  mounted () {
  },
  methods: {
    ellipsisText (text, length = 10) {
      text = text || ''
      if (text.length <= 10) {
        return text
      } else {
        const showText = text.slice(0, 9) + '...'
        return `<span title="${text}">${showText}</span>`
      }
    },
    getInfo () {
      this.$get(`/supplier/id`, {id: this.record.id}).then(res => {
        if (res && res.returnCode === 1000) {
          const record = res.dataInfo || {}
          record.areaIdList = record.areaTreePath ? record.areaTreePath.split(',') : []
          this.suppStatus = record.suppStatus || null
          this.$nextTick(()=> {
            const formItems = this.form.getFieldsValue();
            Object.keys(formItems).forEach(key => {
              formItems[key] = record[key]
            })
            this.form.setFieldsValue(formItems);
          })
        }
      })
    },
    getType(){
      this.supplierTypeLoading = true
      this.$get(`/supplier/type/list`, {}).then(res => {
        this.supplierTypeLoading = false
        if (res && res.returnCode === 1000 && res.dataInfo && res.dataInfo.length) {
          this.supplierType = res.dataInfo.map(item => {
            item.label = item.typeName
            item.value = item.id
            return item
          })
        }
      }).catch(err=> {
        this.supplierTypeLoading = false
      })
    },
    getBankOpenNameList() {
      this.$get(`/bank/information/list`, {}).then(res => {
        if (res && res.returnCode === 1000 && res.dataInfo && res.dataInfo.length) {
          this.bankOpenNameList = res.dataInfo.map(item => {
            item.label = item.bankName
            item.value = item.id
            return item
          })
        }
      }).catch(err=> {
        this.bankOpenNameList = []
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.indexOf(input) >= 0
      );
    },
    changeBankOpenName(val) {
      this.bankOpenName = this.bankOpenNameList.filter(item => item.value == val)[0].label
    },
    handleSubmit () {
      this.confirmLoading = true
      this.form.validateFields((err, values) => {
        if (!err) {
          values.bankOpenName = this.bankOpenName
          const url = this.record.id ? '/supplier/update' : '/supplier/add'
          const suppStatus = this.record.id ? this.suppStatus : '1'
          const areaInfo = this.getAreaSubmitInfo(values.areaIdList)
          const areaId = Array.isArray(values.areaIdList) ? values.areaIdList[values.areaIdList.length - 1] : ''
          const areaTreePath = Array.isArray(values.areaIdList) ? values.areaIdList.join(',') :''
          const fullAddress = areaInfo.province + areaInfo.city + areaInfo.area + areaInfo.street + (values.detailAddress || '')
          delete values.areaIdList
          // values.supplierContactsAddRequestList.forEach(item => {
          //   if (item.id.indexOf('contract-') === 0) {
          //     delete item.id
          //   }
          // })
          this.$post(url, {...values,
           id: this.record.id,
           suppStatus:suppStatus,
           areaId,
           areaTreePath,
           fullAddress
           }).then(res => {
            this.confirmLoading = false
            if (res && res.returnCode === 1000) {
              this.$message.success('保存成功！')
              this.closeModal(true)
            }
          }).catch(err=> {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      });
    },
    getAreaSubmitInfo (areaIdList=[]) {
      const lastId = areaIdList[areaIdList.length - 1]
      const areaNameList = treeFindPath(this.areaTree, data=>lastId == data.id, [],'areaName')
      const areaList = zip(areaIdList, areaNameList) // 返回 [[省id, 省name], [市id, 市name], [区id, 区name], [街道id, 街道name]]
      const areaInfo = {
        provinceCode: areaList[0] && areaList[0][0] || '',
        province: areaList[0] && areaList[0][1] || '',
        cityCode: areaList[1] && areaList[1][0] || '',
        city: areaList[1] && areaList[1][1] || '',
        areaCode: areaList[2] && areaList[2][0] || '',
        area: areaList[2] && areaList[2][1] || '',
        streetCode: areaList[3] && areaList[3][0] || '',
        street: areaList[3] && areaList[3][1] || '',
      }
      return areaInfo
    },
    closeModal (freshTable) {
      this.form.resetFields()
      this.$emit('cancel', freshTable)
    },
    closeTypeModal (freshTable) {
      this.typeVisible = false
      if (freshTable) {
        this.getType()
      }
    },
    addType (record) {
      this.typeRecord = record
      this.typeVisible = true
    },
  }
}
</script>
<style rel='stylesheet/less' lang='less' scoped>
  .supplier-info{
    margin-bottom: 40px;
    .title {
      // font-weight: bold;
      font-size: 20px;
      margin-left: 50px;
      margin-bottom: 20px;
    }
    // .title{
    //   font-size: 20px;
    //   color: #000000;
    //   margin: 0 0 20px 50px;
    //   .contacts{
    //     font-size: 14px;
    //     margin-left: 20px;
    //   }
    // }
    .fs14{
      font-size: 14px;
    }
    .ml20{
      margin-left: 20px;
    }
  }
</style>